<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>key的作用</title>
</head>
<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入react核心库 -->
    <script src="../js/17/react.development.js" ></script>
    <!-- 引入react-dom，用于支持react操作DOM -->
    <script src="../js/17/react-dom.development.js"></script>
    <!-- 引入babel，用于将jsx转为js -->
    <script src="../js/babel.js" ></script>
    <script type="text/babel"> /*此处一定要写babel，否则无法识别jsx语法*/
        // 创建组件
        class Persons extends React.Component {
            state = {
                persons: [
                    {id: 1, name: '小张', age: 18},
                    {id: 2, name: '小李', age: 19},
                ]
            }
            addRerson = () => {
                const { persons } = this.state
                const p = {
                    id: persons.length + 1, name: '小王', age: 20
                }
                this.setState({
                    persons: [p, ...persons]
                })
            }
            render () {
                return (
                    <div>
                        <h2>展示个人信息</h2>
                        <button onClick={this.addRerson}>添加一个小王</button>
                        <h2>使用index（索引值）作为key</h2>
                        <ul>
                            {
                               this.state.persons.map((personObj, index) => {
                                    return <li key={index}>{personObj.name} --- {personObj.age}<input type="text" /></li>
                               })     
                            }
                        </ul>
                        <h2>使用id（数据的唯一标识）作为key</h2>
                        <ul>
                            {
                               this.state.persons.map((personObj) => {
                                    return <li key={personObj.id}>{personObj.name} --- {personObj.age}<input type="text" /></li>
                               })     
                            }
                        </ul>
                    </div>
                )
            }
        }
        ReactDOM.render(<Persons />, document.getElementById('test'))

    </script>
</body>
</html>